package com.gm.commonlib.views.choiceview;


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.PopupWindow;
import android.widget.ScrollView;

import androidx.appcompat.widget.AppCompatButton;


import com.gm.commonlib.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CustomItemChosenButton extends AppCompatButton implements OnClickListener, OnItemClickListener,
        OnItemLongClickListener, PopupWindow.OnDismissListener {

    public static final int DEFAULT_INPUT_LENGTH = 5;
    public static final String DEFAULT_DEL_KEY = "删除";
    public static final String DEFAULT_DONE_KEY = "完成";

    private PopupWindow mPopupWindow;
    private CustomItemChoosenView mChoosenView;
    private IOnCustomItemClickListener mOnCustomItemClickListener;
    private IOnCustomItemContentChangedListener mIOnCustomItemContentChangedListener;
    private PopupWindow.OnDismissListener mOnDismissListener;
    private List<CustomItemChoosenEntity> mCustomItemList;
    private String mCustomItemTitle;
    private boolean mMultipleInputFlag = false;
    private int mInputLength = DEFAULT_INPUT_LENGTH;
    private int mNumColumns = 5;
    private CustomItemChoosenEntity mChoosenEntity;
    private int mChoosenPosition;
    private boolean mRefreshButtonTextFlag = true;
    private int maxRow = -1;
    private ScrollView mScrollView;

   private OnClickListener onClicklistener;
   public void setCustomOnClickListener(OnClickListener listener){
       onClicklistener=listener;
   }
    public CustomItemChosenButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initAttributeSet(context, attrs);

    }

    public CustomItemChosenButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttributeSet(context, attrs);
    }
    boolean isShowDefaultText;
    public void setIsShowDefaultData(boolean isShowDefaultText){
        this.isShowDefaultText=isShowDefaultText;
    }
    public CustomItemChosenButton(Context context) {
        super(context);
    }

    private void initAttributeSet(Context context, AttributeSet attrs) {
        if (!isInEditMode()) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.fkhview);
            if (a != null) {
                int res = a.getResourceId(R.styleable.fkhview_arrayres, 0);
                if (res > 0) {
                    String[] data = context.getResources().getStringArray(res);
                    if (data != null && data.length > 0) {
                        List<String> list = Arrays.asList(data);
                        mCustomItemList = new ArrayList<CustomItemChoosenEntity>();
                        for (String item : list) {
                            mCustomItemList.add(new StringEntity(item));
                        }
                    }
                }
                int titleRes = a.getResourceId(R.styleable.fkhview_itemtitle, 0);
                isShowDefaultText= a.getBoolean(R.styleable.fkhview_isShowFirstText, true);
                if (titleRes > 0) {
                    mCustomItemTitle = context.getResources().getString(titleRes);
                } else {
                    mCustomItemTitle = a.getString(R.styleable.fkhview_itemtitle);
                }
                mMultipleInputFlag = a.getBoolean(R.styleable.fkhview_multiple, false);
                mInputLength = a.getInteger(R.styleable.fkhview_mulLength, DEFAULT_INPUT_LENGTH);
                mNumColumns = a.getInteger(R.styleable.fkhview_numColumns, 5);
                maxRow = a.getInteger(R.styleable.fkhview_maxRow, -1);
                if (!mMultipleInputFlag && mCustomItemList != null && !mCustomItemList.isEmpty()) {
                    mChoosenEntity = mCustomItemList.get(0);
                    mChoosenPosition = 0;
                    if (mRefreshButtonTextFlag && isShowDefaultText) {
                        setText(mCustomItemList.get(0).getText());
                    }
                }
                a.recycle();
            }
        }
    }

    public void resetData(String data) {
        setText(data);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        if (!isInEditMode()) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.custom_item_choosen_button_popupwin, null, false);
            mChoosenView = (CustomItemChoosenView) view
                    .findViewById(R.id.custom_item_choosen_edittext_popwin_choosenview);
            mPopupWindow = new PopupWindow(this);
            mPopupWindow.setWidth(LayoutParams.MATCH_PARENT);
            mPopupWindow.setHeight(LayoutParams.MATCH_PARENT);
            mPopupWindow.setContentView(view);
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOnDismissListener(this);
            int color = 0x90000000;
            if (mMultipleInputFlag) {
                color = 0x00000000;
            }
            mPopupWindow.setTouchable(true);
            ColorDrawable dw = new ColorDrawable(color);
            mPopupWindow.setBackgroundDrawable(dw);
            setOnClickListener(this);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mPopupWindow.isShowing()) {
                        mPopupWindow.dismiss();
                    }
                }
            });
            mChoosenView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            if (mCustomItemList != null) {
                mChoosenView.setDataList(mCustomItemList);
                mChoosenView.setNumColumns(mNumColumns);
            }
            mChoosenView.setTitle(mCustomItemTitle);
            mChoosenView.setMaxRow(maxRow);
            mChoosenView.setOnItemClickListener(this);
            mChoosenView.setOnItemLongClickListener(this);
        }
    }
    public void setMaxRow(int maxRow){
        this.maxRow=maxRow;
        mChoosenView.setMaxRow(maxRow);
    }

    public void setGridViewMaxHeight(int height){
        if (mChoosenView!=null){
            mChoosenView.setGridViewMaxHeight(height);
        }
    }

    public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
        mOnDismissListener = listener;
    }



    @Override
    public void onClick(View v) {
        if (onClicklistener!=null){
            onClicklistener.onClick(v);
        }
        if (mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        } else if(mCustomItemList != null && !mCustomItemList.isEmpty()){
            InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            // 强制隐藏键盘
            imm.hideSoftInputFromWindow(getWindowToken(), 0);
            postDelayed(new Runnable() {

                @Override
                public void run() {
                    mPopupWindow.showAtLocation(CustomItemChosenButton.this, Gravity.BOTTOM
                            | Gravity.CENTER_HORIZONTAL, 0, 0);
                    scrollToShowButton();
                }
            }, 150);
        } else {

        }
    }

    public void show(){
        if (mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
        postDelayed(new Runnable() {

            @Override
            public void run() {
                mPopupWindow.showAtLocation(CustomItemChosenButton.this, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                scrollToShowButton();
            }
        }, 150);
    }

    public String getChoosenCity() {
        return getText().toString();
    }

    public void hiddenChoosenView() {
        if (mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
    }

    public void hiddenTitle(){
        if (mChoosenView!=null){
            mChoosenView.hiddenTitle();
        }

    }

    @Override
    public void onDismiss() {
        if (mOnDismissListener != null) {
            mOnDismissListener.onDismiss();
        }
    }

    public interface IOnCustomItemClickListener {
        void onItemChoosenButtonClick(CustomItemChosenButton button, int itemText, CustomItemChoosenEntity entity);
    }

    public interface IOnCustomItemContentChangedListener {
        void onItemContentChanged(CustomItemChosenButton button, int position, String content);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        String item = mCustomItemList.get(arg2).getText();

            if (mMultipleInputFlag) {
                String str = getText().toString();
                if (DEFAULT_DEL_KEY.equals(item)) {
                    if (str != null) {
                        if (str.length() >= 1) {
                            str = str.substring(0, str.length() - 1);
                            setText(str);
                        }
                    }
                } else if (DEFAULT_DONE_KEY.equals(item)) {
                    if (mPopupWindow.isShowing()) {
                        mPopupWindow.dismiss();
                    }
                } else {
                    if (str != null) {
                        if (mInputLength <= 0 || str.length() < mInputLength) {
                            str += item;
                            setText(str);
                        }
                    } else {
                        setText(item);
                    }
                }
                if (mIOnCustomItemContentChangedListener != null) {
                    mIOnCustomItemContentChangedListener.onItemContentChanged(this, arg2, getText().toString());
                }
                scrollToShowButton();
            } else {
                if (mRefreshButtonTextFlag) {
                    setText(item);
                }
                if (mIOnCustomItemContentChangedListener != null) {
                    mIOnCustomItemContentChangedListener.onItemContentChanged(this, arg2, getText().toString());
                }
                if (mOnCustomItemClickListener != null) {
                    mOnCustomItemClickListener.onItemChoosenButtonClick(this, arg2, mCustomItemList.get(arg2));
                }
                mChoosenEntity = mCustomItemList.get(arg2);
                mChoosenPosition = arg2;
            }

        if (!mMultipleInputFlag && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        String item = mCustomItemList.get(position).getText();
        if (mMultipleInputFlag ) {
            if (DEFAULT_DEL_KEY.equals(item)) {
                setText("");
            }
            scrollToShowButton();
        }
        return false;
    }

    public void resetText() {
        if (!mMultipleInputFlag && mCustomItemList != null && !mCustomItemList.isEmpty()) {
            setText(mCustomItemList.get(0).getText());
            mChoosenEntity = mCustomItemList.get(0);
            mChoosenPosition = 0;
        }
    }

    public void setOnCustomItemClickListener(IOnCustomItemClickListener mOnCustomItemClickListener) {
        this.mOnCustomItemClickListener = mOnCustomItemClickListener;
    }

    public void setOnCustomItemContentChangedListener(IOnCustomItemContentChangedListener mOnCustomItemClickListener) {
        this.mIOnCustomItemContentChangedListener = mOnCustomItemClickListener;
    }

    public void setCustomItemList(List<? extends CustomItemChoosenEntity> list) {
        if (mCustomItemList != null) {
            mCustomItemList.clear();
        } else {
            mCustomItemList = new ArrayList<CustomItemChoosenEntity>();
        }
        if (list != null && !list.isEmpty()) {
            mCustomItemList.addAll(list);
            mChoosenView.setDataList(mCustomItemList);
            if (mRefreshButtonTextFlag && isShowDefaultText) {
                setText(mCustomItemList.get(0).getText());
            }
            mChoosenEntity = mCustomItemList.get(0);
            mChoosenPosition = 0;
            mChoosenView.setNumColumns(mNumColumns);
        }
    }

    public void initData(List<? extends CustomItemChoosenEntity> list) {
        if (mCustomItemList != null) {
            mCustomItemList.clear();
        } else {
            mCustomItemList = new ArrayList<CustomItemChoosenEntity>();
        }
        if (list != null && !list.isEmpty()) {
            mCustomItemList.addAll(list);
            if (mChoosenView!=null){
                mChoosenView.setDataList(mCustomItemList);
            }
            mChoosenEntity = mCustomItemList.get(0);
            mChoosenPosition = 0;

        }
    }

    public void setNum(int num){
        this.mNumColumns=num;
        if (mChoosenView!=null){
            mChoosenView.setNumColumns(num);
        }
    }

    public void setCustomItemList(List<? extends CustomItemChoosenEntity> list, boolean selectFirst) {
        if (mCustomItemList != null) {
            mCustomItemList.clear();
        } else {
            mCustomItemList = new ArrayList<CustomItemChoosenEntity>();
        }
        if (list != null && !list.isEmpty()) {
            mCustomItemList.addAll(list);
            mChoosenView.setDataList(mCustomItemList);
            if (selectFirst) {
                setText(mCustomItemList.get(0).getText());
                mChoosenEntity = mCustomItemList.get(0);
                if (mOnCustomItemClickListener != null) {
                    mOnCustomItemClickListener.onItemChoosenButtonClick(this, 0, mChoosenEntity);
                }
            } else {
                mChoosenEntity = null;
            }
            mChoosenPosition = 0;
            mChoosenView.setNumColumns(mNumColumns);
        }
    }

    public void setCustomStringList(List<String> list) {
        if (list != null && !list.isEmpty()) {
            List<StringEntity> newList = new ArrayList<StringEntity>();
            for (String str : list) {
                newList.add(new StringEntity(str));
            }
            setCustomItemList(newList);
        }
    }

    public void setArrayStringRes(Context context, int arrayRes) {
        if (context != null) {
            try {
                String[] data = context.getResources().getStringArray(arrayRes);
                if (data.length > 0) {
                    setCustomStringList(Arrays.asList(data));
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    public void setRefreshButtonTextFlag(boolean mRefreshButtonTextFlag) {
        this.mRefreshButtonTextFlag = mRefreshButtonTextFlag;
    }

    public void setInputLength(int mInputLength) {
        this.mInputLength = mInputLength;
    }

    public CustomItemChoosenEntity getChoosenItem() {
        if (mMultipleInputFlag) {
            return null;
        }
        return mChoosenEntity;
    }

    public void clean() {
        setText("");
        mChoosenEntity = null;
    }

    public int getChoosenPosition() {
        return mChoosenPosition;
    }

    public void setChoosenPosition(int position) {
        if (position >= 0 && position < mCustomItemList.size()) {
            mChoosenPosition = position;
            mChoosenEntity = mCustomItemList.get(position);
            setText(mChoosenEntity.getText());
        }
    }

    public void choicePosition(int position) {
        if (position >= 0 && position < mCustomItemList.size()) {
            mChoosenPosition = position;
            mChoosenEntity = mCustomItemList.get(position);
            setText(mChoosenEntity.getText());

            if (mIOnCustomItemContentChangedListener != null) {
                mIOnCustomItemContentChangedListener.onItemContentChanged(this, position, getText().toString());
            }
            if (mOnCustomItemClickListener != null) {
                mOnCustomItemClickListener.onItemChoosenButtonClick(this, position, mCustomItemList.get(position));
            }
        }
    }



    public List<CustomItemChoosenEntity> getmCustomItemList() {
        return mCustomItemList;
    }

    private static class StringEntity implements CustomItemChoosenEntity {

        String item;

        public StringEntity(String item) {
            this.item = item;
        }

        @Override
        public String getText() {
            // TODO Auto-generated method stub
            return item;
        }
    }

    private void scrollToShowButton() {
        if (mScrollView != null) {
            post(new Runnable() {
                @Override
                public void run() {
                    int a[] = new int[2];
                    int b[] = new int[2];
                    getLocationOnScreen(a);
                    Rect buttonRect = new Rect();
                    buttonRect.top = a[1];
                    buttonRect.bottom = a[1] + getHeight();
                    final int offset;
                    if (mPopupWindow.isShowing()) {
                        mChoosenView.getLocationOnScreen(b);
                        offset = buttonRect.bottom - b[1];
                        if (offset > 0) {
                            mScrollView.smoothScrollBy(0, offset);
                        }
                    }
                }
            });
        }
    }

    public void setScrollView(ScrollView mScrollView) {
        this.mScrollView = mScrollView;
    }









}
